import { defineStore } from 'pinia';
import { ref, computed } from 'vue';
import { precisionAdd, precisionMultiply } from '@/utils/precision';
import { useNurseGoods } from '@/service';
import { getNightList, getUrgentList, getExpertList, getDistanceList, getFeeControl } from '@/service/api/nurse_goods';
import Taro from '@tarojs/taro';
import { request } from '@/service/request';
import dayjs from 'dayjs';
import { localStg } from '@/utils';
type FeeControl = {
  distance: boolean;
  expert: boolean;
  festival: boolean;
  night: boolean;
  spec: boolean;
  urgent: boolean;
  pick: boolean;
};


export const useGoodsStore = defineStore('goods-store', () => {
  // State
  const beginDate = ref('');
  const endDate = ref('');
  const unitTime = ref(1);
  const family = ref<any>({});
  const duration = ref(0);
  const price = ref(0);
  const times = ref(1);
  const remark = ref('');

  const feeControl = ref<FeeControl>({
    distance: false,
    expert: false,
    festival: false,
    night: false,
    spec: false,
    urgent: false,
    pick: false,
  });

  // 加急
  const urgent = ref({
    choose: false,
    fee: 0,
    cur: {},
    options: [
      { text: '3-6小时入户加400(不含夜班)', fee: 400 },
      { text: '6-24小时入户加200(不含夜班)', fee: 200 },
      { text: '24-48小时入户加0(不含夜班)', fee: 0 },
    ],
  });

  // 夜班
  const night = ref({
    choose: false,
    fee: 0,
    price: 1000,
    options: []
  });

  // 节假日
  const festival = ref({
    choose: false,
    fee: 0,
  });

  // 专家
  const expert = ref({
    choose: false,
    fee: 0,
    cur: {},
    options: [
      { text: '0元', fee: 0 },
      { text: '200元', fee: 200 },
      { text: '400元', fee: 400 },
      { text: '600元', fee: 600 },
    ],
  });

  // 接送
  const pickup = ref({
    choose: false,
    fee: 0,
    price: 3000,
  });

  // 规格
  const sku = ref({
    cur: {},
    fee: 0,
    options: [],
  });

  // 距离
  const distance = ref({
    num: 0,
    times: 0,
    fee: 0,
    id: -1,
    options: [],
  });

  const isHoliday = ref(false)

  // Computed getters  
  const baseFare = computed(() => {
    // return distance.value.options[0]?.fee || 0;
    const options = distance.value.options;

    if (!options.length) {
      return 0;
    }

    // 获取各个费用规则
    const baseFareRule = options.find((option: any) => option.feeType === "1"); // 起步价
    return baseFareRule?.fee || 0;
  });

  const urgentFree = computed(() => {
    if (!feeControl.value.urgent) {
      return 0;
    }
    return urgent.value.cur?.fee || 0;
  });

  const nightFree = computed(() => {
    if (!feeControl.value.night) {
      return 0;
    }
    return night.value.choose ? night.value.options[0]?.fee : 0;
  });

  const expertFree = computed(() => {
    if (!feeControl.value.expert) {
      return 0;
    }
    return expert.value.cur?.fee || 0;
  });

  const expertTotalFee = computed(() => {
    let total = expertFree.value;
    if (festival.value.choose) {
      total += expertFree.value;
    }
    total += expertFree.value * overTimes.value;
    return Math.round(total * 100) / 100;
  });

  const distanceTotalFee = computed(() => {
    if (!feeControl.value.distance) {
      return 0;
    }
    let total = distanceFee.value;
    total += baseFare.value * overTimes.value;
    total += pickup.value.choose ? distanceFee.value : 0;
    total += festival.value.choose ? baseFare.value : 0;
    return total;
  });

  const distanceFee = computed(() => {
    if (!feeControl.value.distance) {
      return 0;
    }
    const distanceNum = distance.value.num;
    const options = distance.value.options.filter(i=>i.validate=='1')
    const total = calculateWellFee(distanceNum, options)
    return total

    // if (!options.length) {
    //   return 0;
    // }

    // let totalFee = 0;

    // // 获取各个费用规则
    // const baseFareRule = options.find((option: any) => option.feeType === "1"); // 起步价
    // const midRangeRule = options.find((option: any) => option.feeType === "2"); // 5-10公里
    // const longRangeRule = options.find((option: any) => option.feeType === "3"); // 10公里以上

    // // 起步价（必须有）
    // if (baseFareRule) {
    //   totalFee += baseFareRule.fee;
    //   distance.value.id = baseFareRule.id;
    // }

    // // 5-10公里段费用
    // if (midRangeRule && distanceNum >= midRangeRule.beginKm) {
    //   if (distanceNum <= midRangeRule.endKm) {
    //     // 距离在5-10公里之间
    //     totalFee += midRangeRule.fee;
    //     distance.value.id = midRangeRule.id;
    //   } else {
    //     // 距离超过10公里，5-10公里段全额收取
    //     totalFee += midRangeRule.fee;
    //     distance.value.id = midRangeRule.id;
    //   }
    // }

    // // 10公里以上费用（按公里计算）
    // if (longRangeRule && distanceNum > longRangeRule.beginKm) {
    //   const extraDistance = distanceNum - longRangeRule.beginKm;
    //   totalFee += extraDistance * longRangeRule.fee;
    // }

    // return Math.round(totalFee * 100) / 100;
  });

  const festivalFree = computed(() => {
    if (!feeControl.value.festival) {
      return 0;
    }
    return isHoliday.value ? baseFare.value + expertFree.value : 0;
  });

  const pickupFree = computed(() => {
    if (!feeControl.value.pick) {
      return 0;
    }
    return pickup.value.choose ? distanceFee.value : 0;
  });

  const overtimeFee = computed(() => {
    return overTimes.value * (baseFare.value + expertFree.value);
  });

  const overTimes = computed(() => {
    if (!beginDate.value || !endDate.value) {
      return 0;
    }

    const startTime = new Date(beginDate.value);
    const endTime = new Date(endDate.value);

    // 计算时间差（毫秒）
    const timeDiff = endTime.getTime() - startTime.getTime();
    const min = duration.value || 60;
    const hours = Math.ceil(timeDiff / (1000 * 60 * min));
    return Math.max(hours - 1, 0);
  });

  const totalFee = computed(() => {
    const skuPrice = precisionAdd(sku.value.cur?.price || 0, price.value || 0);
    let t = skuPrice;
    t = precisionAdd(t, urgentFree.value);
    t = precisionAdd(t, nightFree.value);
    t = precisionAdd(t, expertFree.value);
    t = precisionAdd(t, distanceFee.value);
    t = precisionAdd(t, festivalFree.value);
    t = precisionAdd(t, pickupFree.value);
    t = precisionAdd(t, overtimeFee.value);
    return precisionMultiply(t, times.value);
  });

  // Actions
  async function loadSku(code: any) {
    request.get('/standard_price/standardPrice/list', {
      code,
    }, {
      useErrMsg: true
    }).then((res: any) => {
      if (res.success.records.length > 0) {
        sku.value.options = res.success.records;
        sku.value.cur = sku.value.options[0];
      }
      else {
        Taro.showToast({
          title: '商品规格不存在',
          icon: 'none'
        })
      }
    })
  }

  const durationText = computed(() => {
    let t = duration.value || 60;
    if (t < 60) {
      return t + '分钟';
    } else {
      let h = Math.floor(t / 60);
      let m = t % 60;
      let str = h + '小时';
      if (m > 0) {
        str += m + '分钟';
      }
      return str;
    }
  });



  async function init(standardCode: string) {
    try {
      remark.value = '';
      beginDate.value = '';
      endDate.value = '';
      night.value.choose = false;
      urgent.value.choose = false;
      urgent.value.cur = {};
      expert.value.choose = false;
      expert.value.cur = {};
      festival.value.choose = false;
      pickup.value.choose = false;
      pickup.value.fee = 0;
      sku.value.fee = 0;
      sku.value.cur = {};
      distance.value.num = 0;
      feeControl.value = await getFeeControl();

      if (feeControl.value.night) {
        // 初始化夜班费用列表
        const nightResult = await getNightList();

        night.value.options = nightResult.success?.records || [];
      }


      if (feeControl.value.urgent) {
        // 初始化加急费用列表
        const urgentResult = await getUrgentList({});

        urgent.value.options = urgentResult.success?.records || [];
      }

      if (feeControl.value.expert) {
        // 初始化专家费用列表
        const expertResult = await getExpertList();
        expert.value.options = expertResult.success?.records || [];
      }

      if (feeControl.value.distance) {
        // 初始化距离费用列表
       
        // const hospital = localStg.get('defaultHospital') as any;
        const obj = {
          hospital:  Taro.getStorageSync('hospitalName'),
          type: Taro.getStorageSync('typeLevel1') || '',
        }
        // console.log('初始化距离费用列表加载', obj);
        const distanceResult = await getDistanceList(obj);
        distance.value.options = distanceResult.success?.records || [];
      }

      if (feeControl.value.spec) {
        loadSku(standardCode);
      }

    } catch (error) {
      // 商品列表初始化失败
    }
  }

  // 返回所有状态、getters 和 actions
  return {
    feeControl,
    durationText,
    distanceTotalFee,
    expertTotalFee,
    remark,
    times,
    totalFee,
    price,
    family,
    duration,
    // State
    beginDate,
    endDate,
    unitTime,
    urgent,
    night,
    festival,
    expert,
    pickup,
    distance,
    sku,
    isHoliday,

    // Getters (computed)
    baseFare,
    urgentFree,
    nightFree,
    expertFree,
    distanceFee,
    festivalFree,
    pickupFree,
    overtimeFee,

    // Actions
    loadSku,
    init
  };
});

function calculateWellFee(distance, list) {
   // 1. 输入校验
   if (isNaN(distance) || distance < 0) return 0;
   if (!Array.isArray(list) || list.length === 0) return 0;
 
   // 2. 按 beginKm 升序排序（保证起步价是 beginKm 最小的）
   const sortedList = [...list].sort((a, b) => a.beginKm - b.beginKm);
 
   let totalFee = 0;
   sortedList.forEach((rule: any, index: number) => {
    const { beginKm, endKm, fee, feeType } = rule;
    if (index === 0) {
      totalFee += fee;
    } else {
      if(distance > beginKm) {
        if(feeType === "3") {
          totalFee += fee * (Math.min(endKm, distance) - beginKm);
        } else {
          totalFee += fee;
        }
       
      }
    }
   })
   return Math.round(totalFee);
}

